package com.ant.storage.service.impl;

import com.ant.storage.common.ResultCode;
import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.BidInformationDto;
import com.ant.storage.excel.BidInformationExecl;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.BidInformationMapper;
import com.ant.storage.pojo.*;
import com.ant.storage.service.IBidCompanyService;
import com.ant.storage.service.IBidInformationService;
import com.ant.storage.service.IPurchaserRecordImgService;
import com.ant.storage.utils.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author melon
 * @DS("second")
 * @since 2023-12-12
 */
@Service
public class BidInformationServiceImpl extends ServiceImpl<BidInformationMapper, BidInformation> implements IBidInformationService {

    @Autowired
    public ServletContext servletContext;

    @Autowired
    public IBidCompanyService companyService;

    @Autowired
    public IBidInformationService bidInformationService;

    @Autowired
    public IPurchaserRecordImgService imgService;

    @Override
    public PageInfo<BidInformation> queryList(BidInformationDto dto) {
        try {
            UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
            PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<BidInformation> wrapper = new QueryWrapper<>();
            if (dto.getCityId() != null) {
                wrapper.lambda().in(BidInformation::getCityId, dto.getCityId());
            }
            if (dto.getCompanyId() != null) {
                wrapper.lambda().eq(BidInformation::getCompanyId, dto.getCompanyId());
            }
            if (dto.getIsEnroll() != null) {
                wrapper.lambda().eq(BidInformation::getIsEnroll, dto.getIsEnroll());
            }
            if (dto.getIsBid() != null) {
                wrapper.lambda().eq(BidInformation::getIsBid, dto.getIsBid());
            }
            if (StringUtils.isNotEmpty(dto.getContractNumber())) {
                wrapper.lambda().eq(BidInformation::getContractNumber, dto.getContractNumber());
            }
            if (dto.getStatus() != null) {
                wrapper.lambda().eq(BidInformation::getStatus, dto.getStatus());
            }
            // if (StringUtils.isNotEmpty(dto.getPushTime())) {
            if (dto.getPushTime() != null && dto.getPushTime().size() > 0) {
                wrapper.lambda().between(BidInformation::getPushTime,
                        dto.getPushTime().get(0) + " 00:00:00",
                        dto.getPushTime().get(1) + " 23:59:59");
            }
            if (dto.getTime() != null && dto.getTime().size() > 0) {
                wrapper.lambda().between(BidInformation::getCreationTime,
                        dto.getTime().get(0) + " 00:00:00",
                        dto.getTime().get(1) + " 23:59:59");
            }
            //            if (userInfo.getRoles() == null) {
            //                wrapper.lambda().eq(BidInformation::getCityId, userInfo.getCityId()).or().eq
            //                (BidInformation::getCreateBy, userInfo.getNameId());
            //            }
            //            if (userInfo.getRoles() != null && userInfo.getRoles().equals("admin")) {
            //                wrapper.lambda().eq(BidInformation::getCityId, userInfo.getCityId());
            //            }
            wrapper.eq("is_delete", 1);
            wrapper.orderByDesc("id");
            List<BidInformation> list = this.baseMapper.selectList(wrapper);
            list.stream().forEach(item -> {
                item.setCompanyList(companyService.list(new QueryWrapper<BidCompany>().eq("bid_information_id",
                        item.getId())));
            });
            PageInfo<BidInformation> pageInfo = new PageInfo<>(list);
            return pageInfo;
        } catch (Exception e) {
            throw new AntException(ResultCode.BODY_NOT_MATCH.getResultCode(), e.getMessage());
        }
    }

    @Override
    public ResultVo BidInformationSave(BidInformation dto, BindingResult result) {
        synchronized (this) {
            if (result.hasErrors()) {
                throw new AntException(result.getFieldError().getDefaultMessage());
            } else {
                UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
                if (dto.getCompanyId() == null) {
                    dto.setCompanyId(userInfo.getDepId());
                }
                dto.setContractNumber(RandomUtil.generateOrderCode());
                dto.setCityId(userInfo.getCityId());
                dto.setCreateBy(userInfo.getNameId().toString());
                dto.setCreationTime(new Date());
                if (dto.getId() == null) {
                    bidInformationService.save(dto);
                } else {
                    this.baseMapper.updateById(dto);
                }
                return ResultVo.success("操作成功");
            }
        }
    }

    @Override
    public List<BidInformation> bidInformationUserList() {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        if (userInfo.getCityId() == null || userInfo.getDepId() == null) {
            throw new AntException(ResultCode.NOT_FOUND.getResultCode(), "请绑定个人信息");
        }
        return this.baseMapper.selectList(new QueryWrapper<BidInformation>().orderByDesc("id"));
    }

    @Override
    public BidInformation findBidInformationById(Integer id) {
        if (id == null) {
            throw new AntException(ResultCode.FAILURE.getResultCode(), "参数错误");
        } else {
            BidInformation one = this.baseMapper.selectOne(new QueryWrapper<BidInformation>().eq("id", id));

            if (one.getBidDocument() != null) {
                List<PurchaserRecordImg> list1 = imgService.list(new QueryWrapper<PurchaserRecordImg>()
                        .in("id", one.getBidDocument().split(",")));
                one.setBidDocumentList(list1);
            }
            if (one.getBidAnnex() != null) {
                List<PurchaserRecordImg> list2 = imgService.list(new QueryWrapper<PurchaserRecordImg>()
                        .in("id",
                                Arrays.asList(one.getBidAnnex().split(","))));
                one.setBidAnnexList(list2);
            }
            if (one.getBidAnnouncement() != null) {
                List<PurchaserRecordImg> list3 = imgService.list(new QueryWrapper<PurchaserRecordImg>()
                        .in("id",
                                Arrays.asList(one.getBidAnnouncement().split(","))));
                one.setBidAnnouncementList(list3);
            }

            if (one == null) {
                throw new AntException(ResultCode.FAILURE.getResultCode(), "数据不存在");
            }
            one.setCompanyList(companyService.list(new QueryWrapper<BidCompany>().eq("bid_information_id", id)));
            return one;
        }
    }


    @Override
    public Boolean updateTendering(List<ReimburseDetail> list, Integer id) {
        if (list == null || list.size() == 0) {
            return false;
        }
        BidInformation information = new BidInformation();
        list.stream().forEach(item -> {
            if (item.getTypeId() == 29) {
                information.setRegistrationFee(item.getProjectPrice());
            }
            if (item.getTypeId() == 30) {
                information.setPrintingFee(item.getProjectPrice());
            }
            if (item.getTypeId() == 31) {
                information.setBidSecurity(item.getProjectPrice());
            }
            if (item.getTypeId() == 32) {
                information.setPerformanceBond(item.getProjectPrice());
            }
            if (item.getTypeId() == 33) {
                information.setServiceFee(item.getProjectPrice());
            }
            if (item.getTypeId() == 34) {
                information.setServiceFees(item.getProjectPrice());
            }
            if (item.getTypeId() == 35) {
                information.setProcessingFee(item.getProjectPrice());
            }
        });
        bidInformationService.update(information, new QueryWrapper<BidInformation>().eq("id", id));
        return true;
    }

    @Override
    public Boolean isBidInformation(Integer id) {
        BidInformation one = this.baseMapper.selectOne(new QueryWrapper<BidInformation>().eq("id", id));
        if (one == null) {
            return false;
        }
        return true;
    }


    @Override
    public List<BidInformationExecl> exportCensus(Integer copmyId, List<String> time) {
        if (time != null && !time.equals("") && time.size() > 0) {
            String stats = time.get(0) + " 00:00:00";
            String end = time.get(1) + " 23:59:59";
            ArrayList<String> t = new ArrayList<>();
            t.add(stats);
            t.add(end);
            time = t;
        }
        List<BidInformationExecl> list = this.baseMapper.exportCensusList(copmyId, time);
        List<BidInformationExecl> collect = list.stream().map(item -> {
            if (item.getIsEnroll() != null && !item.getIsEnroll().equals("")) {

                if (item.getIsEnroll().equals("1")) {
                    item.setIsEnroll("已报名");
                }
                if (item.getIsEnroll().equals("2")) {
                    item.setIsEnroll("未报名");
                }
                if (item.getIsEnroll().equals("3")) {
                    item.setIsEnroll("跟进中");
                }
            }
            if (item.getIsBid() != null && !item.getIsBid().equals("")) {
                if (item.getIsBid().equals("1")) {
                    item.setIsBid("已投标");
                }
                if (item.getIsBid().equals("2")) {
                    item.setIsBid("未投标");
                }
                if (item.getIsBid().equals("3")) {
                    item.setIsBid("标书制作中");
                }
            }
            if (item.getStatus() != null && !item.getStatus().equals("")) {
                if (item.getStatus().equals("1")) {
                    item.setStatus("已成功");
                }
                if (item.getStatus().equals("2")) {
                    item.setStatus("未成功");
                }
                if (item.getStatus().equals("3")) {
                    item.setStatus("等待通知");
                }
            }
            if (item.getBidMethod() != null && !item.getBidMethod().equals("")) {
                if (item.getBidMethod().equals("1")) {
                    item.setBidMethod("低价中标");
                }
                if (item.getBidMethod().equals("2")) {
                    item.setBidMethod("综合评分");
                }
            }
            if (item.getFailureReason() != null && !item.getFailureReason().equals("")) {
                if (item.getFailureReason().equals("1")) {
                    item.setFailureReason("价格原因");
                }
                if (item.getFailureReason().equals("2")) {
                    item.setFailureReason("资质原因");
                }
                if (item.getFailureReason().equals("3")) {
                    item.setFailureReason("无法运作");
                }
                if (item.getFailureReason().equals("4")) {
                    item.setFailureReason("综合评分低");
                }
                if (item.getFailureReason().equals("5")) {
                    item.setFailureReason("报名原因");
                }
                if (item.getFailureReason().equals("6")) {
                    item.setFailureReason("其他");
                }
            }
            return item;
        }).collect(Collectors.toList());
        return collect;
    }
}
